package com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest;

import android.app.ActivityManager;
import android.content.Context;
import android.os.Environment;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

import java.io.File;

/**
 * @description volley请求管理类 单例
 * @vresion 1.0
 * Created by 安帅 on 2015/10/8 14:30.
 */
public class VolleyRequestManager {
    private static RequestQueue mRequestQueue;
    private static ImageLoader mImageLoader;

    private VolleyRequestManager() {
    }

    public static void init(Context context) {
        mRequestQueue = Volley.newRequestQueue(context);
        //如果sd卡挂载状态，可写入文件，则使用sd卡缓存，最大缓存为20M
        if (getSDPath() != null) {
            int max_cache_size = 1024 * 1024 * 20;
            File file = new File(getSDPath().getAbsolutePath() + "/exiuCache");
            mImageLoader = new ImageLoader(mRequestQueue, new DiskBitmapCache(file, max_cache_size));
        } else {//sd卡不可用，则使用内存缓存，最大缓存为可用缓存的八分之一
            int memClass = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();
            int cacheSize = 1024 * 1024 * memClass / 8;
            mImageLoader = new ImageLoader(mRequestQueue, new BitmapLruCache(cacheSize));
        }
    }

    /**
     * 获取请求队列
     *
     * @return RequestQueue
     */
    public static RequestQueue getRequestQueue() {
        if (mRequestQueue != null) {
            return mRequestQueue;
        } else {
            throw new IllegalStateException("RequestQueue not initialized");
        }

    }

    /**
     * 把请求加入请求队列
     *
     * @param request 请求
     * @param tag     标签
     */
    public static void addRequest(Request<?> request, Object tag) {
        if (tag != null) {
            request.setTag(tag);
        }
        mRequestQueue.add(request);
    }

  /*  public static void cancelAll(Object tag) {
        mRequestQueue.cancelAll(tag);
    }*/

    public static ImageLoader getImageLoader() {
        if (mImageLoader != null) {
            return mImageLoader;
        } else {
            throw new IllegalStateException("ImageLoader not initialized");
        }
    }


    private static File getSDPath() {
        File sdDir = null;
        //判断sd卡是否存在
        boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//获取根目录
        }
        return sdDir;
    }
}
